using System;
using System.Threading.Tasks;
using GameKit.Core;

namespace GameKit.UI
{
    /// <summary>
    /// 抽象UI工具包
    /// </summary>
    /// <typeparam name="TAsset">资源类型</typeparam>
    public abstract class AbsUIKit<TAsset>
    {
        private IAssetLoader _assetLoader;

        public void SetAssetLoader(IAssetLoader assetLoader)
        {
            _assetLoader = assetLoader;
        }

        public async Task<IPanel> OpenPanelAsync(object target, string path)
        {
            TAsset asset = await _assetLoader.LoadAsync<TAsset>(target, path);
            if (asset == null)
            {
                throw new Exception("Load asset failed: " + path);
            }

            var panel = MakePanel(asset);
            panel.Open();
            return panel;
        }

        public void OpenPanel(object target, string path, Action<IPanel> callback)
        {
            _assetLoader.Load<TAsset>(target, path, asset =>
            {
                var panel = MakePanel(asset);
                panel.Open();
                callback.Invoke(panel);
            });
        }

        protected abstract IPanel MakePanel(TAsset asset);
    }
}